import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/home/search_logic.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/mode_config.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/sp_utils.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/search/search_item.dart';
import 'package:sports_new/widgets/base/qkd_dialog.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import '../../entity/home/search/search_entity.dart';
import '../../widgets/base/qkd_text.dart';
import '../../widgets/loading/no_data_widget.dart';
import '../home/home_page.dart';

class SearchPage extends StatefulWidget {
  const SearchPage({Key? key}) : super(key: key);

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  final logic = Get.put(SearchLogic());

  @override
  void initState() {
    logic.focus = FocusNode();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      Future.delayed(const Duration(milliseconds: 400))
          .then((value) {
            FocusScope.of(context).requestFocus(logic.focus);
            logic.getHot();
          });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<SearchLogic>(builder: (logic) {
      return Scaffold(
        appBar: Styles.appBar(
          toolbarHeight: 0,
          backgroundColor: Colours.white,
        ),
        backgroundColor: Colours.scaffoldBg,
        body: SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _searchBar(),
              if(!logic.goSearch)...[
                Expanded(
                  child: MediaQuery.removePadding(
                    removeTop: true,
                    context: context,
                    child: ListView(
                      physics: const ClampingScrollPhysics(),
                      children: logic.hot?.where((element) => element.type != 5 && (ModeConfig.expert?true:element.type!=2)).map(
                        (e) => block(e,needTitle: false)).toList().insertWith(0, [
                          Container(
                          color: Colours.white,
                          child: Column(
                            children: [
                              if(SpUtils.searchHistory.hasValue || logic.hotWord.hasValue)
                              Container(height: 16),
                              if(SpUtils.searchHistory.hasValue)
                                wordArea("历史搜索",SpUtils.searchHistory?.reversed.toList(),needEdit: true),
                              if(logic.hotWord.hasValue)
                                wordArea("热门搜索",
                                  logic.hotWord.map((e) => e.matchInfo ?? "").toList(),
                                  sportsId: logic.hotWord.map((e) => e.sportsId ?? 0).toList(),
                                  id: logic.hotWord.map((e) => e.matchId ?? 0).toList()
                                )
                            ]
                          ),
                        )
                      ]) ?? []
                    ),
                  ),
                )
              ]else...[
                Container(
                  color: Colours.white,
                  height: 40,
                  child: Styles.tabbar(
                    tabs: logic.tabs.map((e) => QkdText(e)).toList(),
                    controller: logic.tabController
                  ),
                ),
                Expanded(
                  child: TabBarView(
                      controller: logic.tabController,
                      children: List.generate(
                        logic.tabs.length,
                        (index) => MediaQuery.removePadding(
                          context: context,
                          removeTop: true,
                          child: LoadingWidget<bool>(
                            isLoading: logic.entity[index] == null,
                            data: logic.entity[index]?.length == 0,
                            noData: const NoDataWidget(
                              needScroll: true,
                              picSize: 160,
                              tip: "暂无内容，换个关键词吧～",
                            ),
                            child: () => ListView(
                              children: index == 0?
                              logic.entity[index]?.where((element) => ModeConfig.expert?element.type!=2:true).map((e) => block(e,margin: const EdgeInsets.only(top: 16))).toList() ?? []:
                              list(index)
                            ),
                          ),
                        )
                    )
                  ),
                )
              ]
            ],
          ),
        ),
      );
    });
  }

  List<Widget> list(int index){
    List<Widget> list = [];
    logic.entity[index]?.forEach(
      (e) => list.addAll(e.list?.map<Widget>(
        (element) => SearchItem(type: index, data: element, searchWord: logic.searchWord)
      ) ?? [])
    );
    return list;
  }

  Widget wordArea(String title,List<String>? text,{List<int>? id,List<int>? sportsId,bool needEdit = false}){
    return Padding(
      padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              QkdText(title,
                fontSize: 16,
                fontWeight: FontWeight.w500
              ),
              const Spacer(),
              if(needEdit)
              Image.asset(
                  Utils.getImgPath("trashcan.png"),width: 20
              ).tap(() async{
                var result = await Get.dialog(
                  const QkdDialog.alert("要清除所有搜索记录吗？")
                );
                if(result == true) SpUtils.deleteSearchHistory();
              }),
            ],
          ),
          Container(height: 16),
          Wrap(
            spacing: 10,runSpacing: 10,
            children: List.generate(
              text?.length ?? 0,
                (index) => wordLabel(
                  text?[index] ?? "",id: id?[index],sportsId: sportsId?[index]
                )
            ),
          ),
        ],
      ),
    );
  }
  
  Widget block(SearchEntity entity,{bool needTitle = true,EdgeInsets? margin}){
    return Padding(
      padding: margin ?? const EdgeInsets.only(bottom: 4),
      child: Column(
        children: [
          if(needTitle)
          Row(
            children: [
              QkdText(logic.tabs[entity.type!],fontSize: 16),
              const Spacer(),
              Row(
                children: [
                  const QkdText("更多",color: Colours.grey66),
                  Image.asset(Utils.getImgPath("arrow_right_36.png"),width: 12)
                ],
              ).tap(() => logic.tabController.animateTo(entity.type!))
            ],
          ).paddingSymmetric(horizontal: 12).paddingOnly(bottom: 4),
          ...entity.list?.map((e) => SearchItem(type: entity.type!, data: e,searchWord: "")).toList() ?? []
        ]
      ),
    );
  }

  Widget _searchBar() {
    return Container(
      color: Colours.white,
      padding: const EdgeInsets.only(top: 5, bottom: 5, right: 16, left: 16),
      child: Row(
        children: [
          GestureDetector(
              onTap: () {
                if(logic.goSearch){
                  logic.goSearch = !logic.goSearch;
                  logic.textController.text = "";
                  logic.str = "";
                  logic.currentIndex = 0;
                  logic.tabController.animateTo(0);
                  update();
                }else{
                  Get.back();
                }
              },
              child: Image.asset(
                Utils.getImgPath('arrow_back.png'),
                width: 24,
              )),
          Expanded(
            child: Hero(
              tag: "searchBar",
              createRectTween: (begin, end) => SearchRectTween(begin,end),
              child: Container(
                padding: const EdgeInsets.only(right: 10),
                height: 34,
                child: TextField(
                    controller: logic.textController,
                    enabled: true,
                    maxLines: 1,
                    style: const TextStyle(fontSize: 16),
                    strutStyle: const StrutStyle(fontSize: 18),
                    cursorColor: Colours.main,
                    focusNode: logic.focus,
                    onTap: () =>
                        FocusScope.of(context).requestFocus(logic.focus),
                    onChanged: (str) {
                      logic.str = str;
                      update();
                    },
                    onTapOutside: (event) => logic.focus.unfocus(),
                    onEditingComplete: () {
                      logic.getSearch();
                      logic.focus.unfocus();
                    },
                    decoration: InputDecoration(
                        filled: true,
                        isCollapsed: true,
                        fillColor: Colours.greyF2F3F7,
                        contentPadding: const EdgeInsets.only(top: 4),
                        prefixIcon: Padding(
                          padding: const EdgeInsets.all(6),
                          child: Image.asset(Utils.getImgPath("search.png"),
                              color: Colours.grey99, width: 16, height: 16),
                        ),
                        suffixIcon: logic.textController.text.isNotEmpty
                            ? GestureDetector(
                            onTap: () {
                              logic.textController.text = '';
                              logic.str = "";
                              logic.goSearch = false;
                              update();
                            },
                            child: Padding(
                              padding: const EdgeInsets.all(8),
                              child: Image.asset(
                                  Utils.getImgPath("search_close.png"),
                                  width: 16, height: 16),
                            )
                        ) : null,
                        border: const OutlineInputBorder(
                            borderSide: BorderSide.none,
                            borderRadius: BorderRadius.all(Radius.circular(35 / 2))),
                        hintText: "搜索${ModeConfig.expert?"专家、方案、":""}赛事、球队等",
                        hintStyle: const TextStyle(fontSize: 14, height: 1.4)),
                  ),
              ),
            ),
          ),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              logic.getSearch();
              logic.focus.unfocus();
            },
            child: const QkdText("搜索",
              color: Colours.main, fontSize: 16)
          )
        ],
      ),
    );
  }

  Widget wordLabel(String text,{int? id,int? sportsId}){
    return GestureDetector(
      onTap: () {
        if(id == null) {
          logic.textController.text = text;
          logic.str = text;
          logic.getSearch();
          update();
        }else{
          Get.toNamed(sportsId == 1?Routes.zqMatchDetail:Routes.lqMatchDetail,arguments: id);
        }
      },
      child: Container(
        constraints: BoxConstraints(maxWidth: Get.width/2-22),
        width: id == null?null:(Get.width-32-10)/2,
        padding: const EdgeInsets.symmetric(horizontal: 12,vertical: 7),
        decoration: BoxDecoration(
          color: Colours.greyF7,
          borderRadius: BorderRadius.circular(4)
        ),
        child: QkdText(text, needCenter: true,maxLines: 1),
      ),
    );
  }

  InlineSpan formSpan(String src, String pattern) {
    List<TextSpan> span = [];
    RegExp regExp = RegExp(pattern, caseSensitive: false);
    src.splitMapJoin(regExp, onMatch: (Match match) {
      span.add(TextSpan(
          text: match.group(0),
          style: const TextStyle(
              fontWeight: FontWeight.w500, color: Colours.main)));
      return '';
    }, onNonMatch: (str) {
      span.add(TextSpan(
          text: str,
          style: const TextStyle(
              fontWeight: FontWeight.w500, color: Colours.text)));
      return '';
    });
    return TextSpan(children: span);
  }
}

